import React, { Suspense } from "react";
import { Route, Switch, Redirect } from "react-router-dom";

import { Spin } from "antd";

// author: YuBing  羽冰
//  time : 2021.4.6
// 自制路由视图组件
// 组件参数: 
//    1. 路由配置（必选）
//    2. 重定向配置(可选)
// 1. 路由配置格式如下:
// const route = [{name,path,component[,children]},{name,path,component[,children]},···]
// 其中children的结构和参数与route相同,即多个children就是和route一样的对象数组,单个children就是单个对象
// 2. 重定向配置如下:
// const redirect = [{ from,to },{ from,to }···]
// 3. 如下
// <RouterView routes={route} redirect={redirect} />
// 注意事项：调用该组件的父组件,整个组件最外围必须有react-router-dom的<Router><Router/>包裹
// ps: Router ----> import {BrowserRouter as Router} from "react-router-dom";

const readRoutes = routes => (
  routes.map(item => {
    if (item.children) return readRoutes(item.children);
    return (
      <Route
        path={item.path}
        key={item.path}
        exact
        component={item.component}
      />
    )
  }
  )
);

const setRedirect = redirectSetting => (
  redirectSetting.map(item => (
    <Redirect from={item.from} to={item.to} key={item.to} exact/>
  ))
)

const loadingStyle = {
  width: "50px",
  height: "50px",
  position: "absolute",
  top: "50%",
  left: "50%",
  marginLeft: "-25px",
  marginTop: "-25px"
}

const RouterView = props => {
  return (
    <>
      <Suspense fallback={<div className="loading" style={loadingStyle}><Spin size="large" /></div>} >
        <Switch>
          {readRoutes(props.routes)}
          {
            props.redirect ?
              setRedirect(props.redirect) : ""
          }
        </Switch>
      </Suspense>
    </>
  )
}

export default RouterView